package com.climber.android

import android.content.Context
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Interceptor
import com.alibaba.android.arouter.facade.callback.InterceptorCallback
import com.alibaba.android.arouter.facade.template.IInterceptor
import com.alibaba.android.arouter.launcher.ARouter
import com.climber.android.commonres.R
import com.climber.android.commonres.app.AppAccount
import com.climber.android.commonsdk.app.AppConstants
import com.climber.android.commonsdk.arouter.ARouterPathConstants
import com.climber.android.commonsdk.arouter.ARouterRoleExtra
import com.climber.android.commonsdk.event.BusProvider
import com.climber.android.commonsdk.event.CommonBusEvent
import io.ganguo.library.mvp.arouter.BundleHelper

/**
 * Created by Mikes at 2019/4/28 10:08 AM
 * 用户角色权限拦截器,运行在非UI线程
 * 拦截处理后，可以再次跳转到目标页面，不打断用户操作流程。
 */
@Interceptor(priority = 1, name = "User Role Interceptor")
class UserRoleInterceptor : IInterceptor {
    override fun process(postcard: Postcard, callback: InterceptorCallback) {
        if(postcard.extra and ARouterRoleExtra.EXTRA_NEED_LOGIN_TOKEN != 0){
            // 需要登录权限的页面
            if(handleLoginTokenPage(postcard, callback)){
                //跳往目标页面
                callback.onContinue(postcard)
            }
        } else{
            // 允许匿名访问的页面
            callback.onContinue(postcard)
        }
    }

    /**
     * @return true, 可以打开目标页面
     */
    private fun handleLoginTokenPage(postcard: Postcard, callback: InterceptorCallback) : Boolean{
        //需要登录才能查看的页面
        if(AppAccount.isAuthenticated()){
            return true
        } else{
            callback.onInterrupt(RuntimeException("you are not allowed to open ${postcard.path} because you are anonymous user."))
            /**
             * 将path传递到login， 登录成功后打开path路径页面.
             */
            BusProvider.getInstance().post(CommonBusEvent.NeedTokenEvent(postCardPath = postcard.path, postCardBundle = postcard.extras))
            return false
        }
    }

    override fun init(context: Context) {

    }
}
